<?php

namespace App\Services\WxCard;

use App\Models\WxCardBase;
use App\Models\WxCardMember;
use App\Models\WxCardMemberList;
use App\Services\EasyWechat;
use App\Services\WxCardMemberLevelService;
use App\Services\WxCardService;
use App\Services\WxErrorService;
use App\Services\WxMaterial\WxMaterialNews;

/**
 * 微信会员卡
 * @package App\Services\WxCard
 */
class WxCardMemberCard extends WxCardAbstract
{
    const STATUS_NORMAL = 'NORMAL';
    const STATUS_EXPIRE = 'EXPIRE';
    const STATUS_GIFTING = 'GIFTING';
    const STATUS_GIFT_SUCC = 'GIFT_SUCC';
    const STATUS_GIFT_TIMEOUT = 'GIFT_TIMEOUT';
    const STATUS_DELETE = 'DELETE';
    const STATUS_UNAVAILABLE = 'UNAVAILABLE';

    const CARD_KEY_COMMON = 'common_card';//通用会员卡


    protected $name = '会员卡';
    protected $cardKeyList = [

    ];

    protected $statusList;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->statusList = [
            self::STATUS_NORMAL => '正常',
            self::STATUS_EXPIRE => '已过期',
            self::STATUS_GIFTING => '转赠中',
            self::STATUS_GIFT_SUCC => '转赠成功',
            self::STATUS_GIFT_TIMEOUT => '转赠超时',
            self::STATUS_DELETE => '已删除',
            self::STATUS_UNAVAILABLE => '已失效',
        ];
        //卡券标识列表
        $this->cardKeyList = [
            self::CARD_KEY_COMMON => '通用会员卡',
        ];
    }

    /**
     * 获取会员卡状态
     * @param $status
     * @return mixed|string
     */
    public function getStatus($status)
    {
        return isset($this->statusList[$status]) ? $this->statusList[$status] : '';
    }

    /**
     * 保存会员卡数据
     * @param $request
     */
    public function save($request)
    {
        \DB::beginTransaction();
        try {
            //保存卡券基础和高级数据
            $cardBaseId = $this->saveBase($request);
            //保存会员卡数据
            $memberId = $request->member['id'] ?? 0;
            if ($memberId) {
                $memberModel = WxCardMember::findOrFail($memberId);
            } else {
                $memberModel = new WxCardMember;
            }
            $memberModel->card_base_id = $cardBaseId;
            $memberModel->background_pic_url = $request->member['background_pic_url'] ?? '';
            $memberModel->prerogative = $request->member['prerogative'] ?? '';
            $memberModel->activate = $request->member['activate'] ?? [];
            $memberModel->service_statement = $request->member['service_statement'] ?? [];
            $memberModel->bind_old_card = $request->member['bind_old_card'] ?? [];
            $memberModel->bonus = $request->member['bonus'] ?? [];
            $memberModel->balance = $request->member['balance'] ?? [];
            $memberModel->custom_field1 = $request->member['custom_field1'] ?? [];
            $memberModel->custom_field2 = $request->member['custom_field2'] ?? [];
            $memberModel->custom_field3 = $request->member['custom_field3'] ?? [];
            $memberModel->custom_cell1 = $request->member['custom_cell1'] ?? [];
            $memberModel->custom_cell2 = $request->member['custom_cell2'] ?? [];
            $memberModel->custom_cell3 = $request->member['custom_cell3'] ?? [];
            $memberModel->bonus_rule = $request->member['bonus_rule'] ?? [];
            $memberModel->discount = (int)$request->member['discount'] ?? 0;
            $memberModel->save();

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 卡券发布
     * @param $cardBaseId
     * @return bool
     * @throws \Exception
     */
    public function publish($cardBaseId)
    {
        $base = \App\Models\WxCardBase::with(['advance', 'member'])->findOrFail($cardBaseId);
        $cardData = $base->toArray();
        //组装卡券公共接口提交数据
        $apiPostData = $this->buildCommonApiPostData($cardData);
        //组装会员卡接口数据
        $memberData = $cardData['member'];
        //商家自定义会员卡背景图
        if (empty($cardData['card_id']) && !empty($memberData['background_pic_url'])) {
            $apiPostData['background_pic_url'] = (new WxMaterialNews())->getWxViewUrl($memberData['background_pic_url']);
        }
        //积分显示
        if (!empty($memberData['bonus'])) {
            if (empty($cardData['card_id'])) {
                $apiPostData['supply_bonus'] = (bool)$memberData['bonus']['supply_bonus'];
            }
            if ($memberData['bonus']['supply_bonus']) {
                //跳转外链查看积分详情
                if (empty($cardData['card_id']) && !empty($memberData['bonus']['bonus_url'])) {
                    $apiPostData['bonus_url'] = $memberData['bonus']['bonus_url'];
                }
                //积分清零规则
                !empty($memberData['bonus']['bonus_cleared']) && $apiPostData['bonus_cleared'] = $memberData['bonus']['bonus_cleared'];
                //积分规则
                !empty($memberData['bonus']['bonus_rules']) && $apiPostData['bonus_rules'] = $memberData['bonus']['bonus_rules'];
            }
        }
        //余额显示
        if (!empty($memberData['balance'])) {
            if (empty($cardData['card_id'])) {
                $apiPostData['supply_balance'] = (bool)$memberData['balance']['supply_balance'];
            }
            if ($memberData['balance']['supply_balance']) {
                //跳转外链查看余额详情
                if (empty($cardData['card_id']) && !empty($memberData['balance']['balance_url'])) {
                    $apiPostData['balance_url'] = $memberData['balance']['balance_url'];
                }
                //储值说明
                !empty($memberData['balance']['balance_rules']) && $apiPostData['balance_rules'] = $memberData['balance']['balance_rules'];
            }
        }
        //特权说明
        !empty($memberData['prerogative']) && $apiPostData['prerogative'] = $memberData['prerogative'];
        //会员卡激活
        if (empty($cardData['card_id'])) {
            if ($memberData['activate']['type'] == 'api') {//接口激活
                !empty($memberData['activate']['activate_url']) && $apiPostData['activate_url'] = $memberData['activate']['activate_url'];
                !empty($memberData['activate']['activate_app_brand_user_name']) && $apiPostData['activate_app_brand_user_name'] = $memberData['activate']['activate_app_brand_user_name'];
                !empty($memberData['activate']['activate_app_brand_pass']) && $apiPostData['activate_app_brand_pass'] = $memberData['activate']['activate_app_brand_pass'];
            } elseif ($memberData['activate']['type'] == 'onekey') {//一键激活
                //普通一键激活
                !empty($memberData['activate']['wx_activate']) && $apiPostData['wx_activate'] = (bool)$memberData['activate']['wx_activate'];
                //跳转型一键激活
                if ($memberData['activate']['wx_activate_after_submit']) {
                    $apiPostData['wx_activate_after_submit'] = (bool)$memberData['activate']['wx_activate_after_submit'];
                    !empty($memberData['activate']['wx_activate_after_submit_url']) && $apiPostData['wx_activate_after_submit_url'] = $memberData['activate']['wx_activate_after_submit_url'];
                }
            } elseif ($memberData['activate']['type'] == 'auto') {//自动激活
                !empty($memberData['activate']['auto_activate']) && $apiPostData['auto_activate'] = (bool)$memberData['activate']['auto_activate'];
            }
        } else {
            if ($memberData['activate']['type'] == 'api') {//接口激活(激活地址可以更改)
                !empty($memberData['activate']['activate_url']) && $apiPostData['activate_url'] = $memberData['activate']['activate_url'];
            }
        }
        //重要自定义会员信息一
        if ($memberData['custom_field1']['isopen']) {
            if (!empty($memberData['custom_field1']['name_type'])) {
                $apiPostData['custom_field1']['name_type'] = $memberData['custom_field1']['name_type'];
            } else {
                $apiPostData['custom_field1']['name'] = $memberData['custom_field1']['name'];
            }
            !empty($memberData['custom_field1']['url']) && $apiPostData['custom_field1']['url'] = $memberData['custom_field1']['url'];
        }
        //重要自定义会员信息二
        if ($memberData['custom_field2']['isopen']) {
            if (!empty($memberData['custom_field2']['name_type'])) {
                $apiPostData['custom_field2']['name_type'] = $memberData['custom_field2']['name_type'];
            } else {
                $apiPostData['custom_field2']['name'] = $memberData['custom_field2']['name'];
            }
            !empty($memberData['custom_field2']['url']) && $apiPostData['custom_field2']['url'] = $memberData['custom_field2']['url'];
        }
        //重要自定义会员信息三
        if ($memberData['custom_field3']['isopen']) {
            if (!empty($memberData['custom_field3']['name_type'])) {
                $apiPostData['custom_field3']['name_type'] = $memberData['custom_field3']['name_type'];
            } else {
                $apiPostData['custom_field3']['name'] = $memberData['custom_field3']['name'];
            }
            !empty($memberData['custom_field3']['url']) && $apiPostData['custom_field3']['url'] = $memberData['custom_field3']['url'];
        }
        //其他自定义会员信息一
        if ($memberData['custom_cell1']['isopen']) {
            !empty($memberData['custom_cell1']['name']) && $apiPostData['custom_cell1']['name'] = $memberData['custom_cell1']['name'];
            !empty($memberData['custom_cell1']['tips']) && $apiPostData['custom_cell1']['tips'] = $memberData['custom_cell1']['tips'];
            !empty($memberData['custom_cell1']['url']) && $apiPostData['custom_cell1']['url'] = $memberData['custom_cell1']['url'];
        }
        //会员卡积分规则设置
        if (empty($cardData['card_id']) && !empty($memberData['bonus_rule'])) {
            !empty($memberData['bonus_rule']['cost_money_unit']) && $apiPostData['bonus_rule']['cost_money_unit'] = (int)$memberData['bonus_rule']['cost_money_unit'];
            !empty($memberData['bonus_rule']['increase_bonus']) && $apiPostData['bonus_rule']['increase_bonus'] = (int)$memberData['bonus_rule']['increase_bonus'];
            !empty($memberData['bonus_rule']['max_increase_bonus']) && $apiPostData['bonus_rule']['max_increase_bonus'] = (int)$memberData['bonus_rule']['max_increase_bonus'];
            !empty($memberData['bonus_rule']['init_increase_bonus']) && $apiPostData['bonus_rule']['init_increase_bonus'] = (int)$memberData['bonus_rule']['init_increase_bonus'];
            !empty($memberData['bonus_rule']['cost_bonus_unit']) && $apiPostData['bonus_rule']['cost_bonus_unit'] = (int)$memberData['bonus_rule']['cost_bonus_unit'];
            !empty($memberData['bonus_rule']['reduce_money']) && $apiPostData['bonus_rule']['reduce_money'] = (int)$memberData['bonus_rule']['reduce_money'];
            !empty($memberData['bonus_rule']['least_money_to_use_bonus']) && $apiPostData['bonus_rule']['least_money_to_use_bonus'] = (int)$memberData['bonus_rule']['least_money_to_use_bonus'];
            !empty($memberData['bonus_rule']['max_reduce_bonus']) && $apiPostData['bonus_rule']['max_reduce_bonus'] = (int)$memberData['bonus_rule']['max_reduce_bonus'];
        }
        //折扣
        if (empty($cardData['card_id']) && !empty($memberData['discount'])) {
            $apiPostData['discount'] = (int)['discount'];
        }
        $app = EasyWechat::officialAccount();
        //提交到微信接口创建或更新卡券信息，保存微信卡券ID
        if (empty($base->card_id)) {
            $apiRs = $app->card->create('MEMBER_CARD', $apiPostData);
            WxErrorService::checkApiResponse($apiRs);
            if (empty($apiRs['card_id'])) {
                throw new \Exception('微信卡号生成失败');
            }
            $base->audit_status = WxCardService::CARD_STATUS_NOT_VERIFY;
            $base->card_id = $apiRs['card_id'];
            $base->save();
        } else {
            $apiRs = $app->card->update($base->card_id, 'MEMBER_CARD', $apiPostData);
            WxErrorService::checkApiResponse($apiRs);
            $base->audit_status = $apiRs['send_check'] == true ? WxCardService::CARD_STATUS_NOT_VERIFY : WxCardService::CARD_STATUS_VERIFY_OK;
            $base->save();
        }
        //如果为一键激活则设置开卡字段接口
        if (!empty($base->card_id) && $memberData['activate']['type'] == 'onekey') {
            $memberUserformPostData = [
                'card_id' => $base->card_id,
            ];
            //服务声明
            if (!empty($memberData['service_statement']['name'])) {
                $memberUserformPostData['service_statement']['name'] = $memberData['service_statement']['name'];
                $memberUserformPostData['service_statement']['url'] = $memberData['service_statement']['url'];
            } else {
                $memberUserformPostData['service_statement']['name'] = '';
                $memberUserformPostData['service_statement']['url'] = '';
            }
            //绑定老会员链接
            if (!empty($memberData['bind_old_card']['name'])) {
                $memberUserformPostData['bind_old_card']['name'] = $memberData['bind_old_card']['name'];
                $memberUserformPostData['bind_old_card']['url'] = $memberData['bind_old_card']['url'];
            } else {
                $memberUserformPostData['bind_old_card']['name'] = '';
                $memberUserformPostData['bind_old_card']['url'] = '';
            }
            //必填项是否可修改
            if (isset($memberData['activate']['required_form_can_modify'])) {
                $memberUserformPostData['required_form']['can_modify'] = (bool)$memberData['activate']['required_form_can_modify'];
            } else {
                $memberUserformPostData['required_form']['can_modify'] = false;
            }
            //选填项是否可修改
            if (isset($memberData['activate']['optional_form_can_modify'])) {
                $memberUserformPostData['optional_form']['can_modify'] = (bool)$memberData['activate']['optional_form_can_modify'];
            } else {
                $memberUserformPostData['optional_form']['can_modify'] = false;
            }
            //表单输入框
            if (!empty($memberData['activate']['field_list'])) {
                foreach ($memberData['activate']['field_list'] as $field) {
                    $field['is_open'] = isset($field['is_open']) ? $field['is_open'] : 0;
                    $field['is_required'] = isset($field['is_required']) ? $field['is_required'] : 0;
                    if ($field['is_open'] == 1) {
                        if ($field['is_common'] == 1 && $field['is_required'] == 1) {//微信格式化项-必填
                            $memberUserformPostData['required_form']['common_field_id_list'][] = $field['type'];
                        }
                        if ($field['is_common'] == 1 && $field['is_required'] != 1) {//微信格式化项-选填
                            $memberUserformPostData['optional_form']['common_field_id_list'][] = $field['type'];
                        }
                        if ($field['is_common'] != 1 && $field['is_required'] == 1) {//自定义选项-必填
                            if ($field['type'] == 'FORM_FIELD_TEXT') {//单行文本
                                $memberUserformPostData['required_form']['custom_field_list'][] = $field['name'];
                            } else {//富文本，单选、下拉选择、多选
                                $memberUserformPostData['required_form']['rich_field_list'][] = [
                                    'type' => $field['type'] ?? '',
                                    'name' => $field['name'] ?? '',
                                    'values' => (array)$field['values'] ?? [],
                                ];
                            }
                        }
                        if ($field['is_common'] != 1 && $field['is_required'] != 1) {//自定义选项-选填
                            if ($field['type'] == 'FORM_FIELD_TEXT') {//单行文本
                                $memberUserformPostData['optional_form']['custom_field_list'][] = $field['name'];
                            } else {
                                $memberUserformPostData['optional_form']['rich_field_list'][] = [
                                    'type' => $field['type'] ?? '',
                                    'name' => $field['name'] ?? '',
                                    'values' => (array)$field['values'] ?? [],
                                ];
                            }
                        }
                    }
                }
            }
            //var_export($memberUserformPostData);exit();
            $apiRs = $app->card->member_card->setActivationForm($base->card_id, $memberUserformPostData);
            WxErrorService::checkApiResponse($apiRs);
        }
        return true;
    }

    /**
     * 同步数据处理
     * @param $cardInfo
     * @return bool
     * @throws \Exception
     */
    public function sync($cardInfo)
    {
        \DB::beginTransaction();
        try {
            //同步基础数据
            $cardBaseId = $this->syncBase($cardInfo);
            //卡券类型
            $cardType = !empty($cardInfo['card_type']) ? $cardInfo['card_type'] : '';
            $dataIndex = strtolower($cardType);
            $cardInfo = !empty($cardInfo[$dataIndex]) ? $cardInfo[$dataIndex] : [];
            //同步会员卡
            $memberModel = WxCardMember::where('card_base_id', $cardBaseId)->first();
            if (empty($memberModel)) {
                $memberModel = new WxCardMember;
            }
            $memberModel->card_base_id = $cardBaseId;
            //自定义会员卡背景图
            if (!empty($cardInfo['background_pic_url'])){
                $memberModel->background_pic_url = (new WxMaterialNews())->getSelfViewUrl($cardInfo['background_pic_url']);
            }
            //会员卡特权说明
            $memberModel->prerogative = $cardInfo['prerogative'] ?? '';
            //会员卡激活信息
            $activate = [
                'type' => 'onekey',
                'field_list' => [
                    ['type' => 'USER_FORM_INFO_FLAG_MOBILE', 'name' => '手机号', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_SEX', 'name' => '性别', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_NAME', 'name' => '姓名', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_BIRTHDAY', 'name' => '生日', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_IDCARD', 'name' => '身份证', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_EMAIL', 'name' => '邮箱', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_LOCATION', 'name' => '详细地址', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_EDUCATION_BACKGROUND', 'name' => '教育背景', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_INDUSTRY', 'name' => '行业', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_INCOME', 'name' => '收入', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ['type' => 'USER_FORM_INFO_FLAG_HABIT', 'name' => '兴趣爱好', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                ],
                'activate_url' => '', 'activate_app_brand_user_name' => '', 'activate_app_brand_pass' => '', 'activate_begin_time' => '', 'activate_end_time' => '',
                'init_bonus' => 0, 'init_bonus_record' => '',
                'init_balance' => 0, 'init_custom_field_value1' => '', 'init_custom_field_value2' => '', 'init_custom_field_value3' => '',
                'auto_activate' => 0, 'wx_activate' => 1,'wx_activate_after_submit' => 0, 'wx_activate_after_submit_url' => '',
                'required_form_can_modify' => 0,
                'optional_form_can_modify' => 0,
            ];
            if (!empty($cardInfo['activate_url'])){//接口激活
                $activate['type'] = 'api';
                $activate['activate_url'] = $cardInfo['activate_url'];
                !empty($cardInfo['activate_app_brand_user_name']) && $activate['activate_app_brand_user_name'] = $cardInfo['activate_app_brand_user_name'];
                !empty($cardInfo['activate_app_brand_pass']) && $activate['activate_app_brand_pass'] = $cardInfo['activate_app_brand_pass'];
            }elseif (isset($cardInfo['wx_activate']) && $cardInfo['wx_activate']){//一键激活
                $activate['type'] = 'onekey';
                $activate['wx_activate'] = 1;
                if (isset($cardInfo['wx_activate_after_submit']) && $cardInfo['wx_activate_after_submit']){
                    $activate['wx_activate_after_submit'] = (int) $cardInfo['wx_activate_after_submit'];
                    $activate['wx_activate_after_submit_url'] = $cardInfo['wx_activate_after_submit_url'] ?? '';
                }

            }elseif (isset($cardInfo['auto_activate']) && $cardInfo['auto_activate']){
                $activate['type'] = 'auto';
                $activate['auto_activate'] = (int) $cardInfo['auto_activate'];
            }
            empty($memberModel->activate) && $memberModel->activate = $activate;
            //服务声明信息
            $serviceStatement = ['name'=>'','url'=>''];
            $memberModel->service_statement = $serviceStatement;
            //绑定老会员链接信息
            $bindOldCard = ['name'=>'','url'=>''];
            $memberModel->bind_old_card = $bindOldCard;
            //积分设置信息
            $bonus['supply_bonus'] = isset($cardInfo['supply_bonus']) ? (int) $cardInfo['supply_bonus'] : 0;
            $bonus['bonus_url'] = !empty($cardInfo['bonus_url']) ? $cardInfo['bonus_url'] : '';
            $bonus['bonus_cleared'] = !empty($cardInfo['bonus_cleared']) ? $cardInfo['bonus_cleared'] : '';
            $bonus['bonus_rules'] = !empty($cardInfo['bonus_rules']) ? $cardInfo['bonus_rules'] : '';
            $memberModel->bonus = $bonus;
            //余额设置信息
            $balance['supply_balance'] = isset($cardInfo['supply_balance']) ? (int) $cardInfo['supply_balance'] : 0;
            $balance['balance_url'] = !empty($cardInfo['balance_url']) ? $cardInfo['balance_url'] : '';
            $balance['balance_rules'] = !empty($cardInfo['balance_rules']) ? $cardInfo['balance_rules'] : '';
            $memberModel->balance = $balance;
            //自定义会员信息类目一
            $customField1 = ['isopen'=>0,'name_type'=>'','name'=>'','url'=>''];
            $customField1['isopen'] = !empty($cardInfo['custom_field1']) ? 1 : 0;
            !empty($cardInfo['custom_field1']['name_type']) && $customField1['name_type'] = $cardInfo['custom_field1']['name_type'];
            !empty($cardInfo['custom_field1']['url']) && $customField1['url'] = $cardInfo['custom_field1']['url'];
            !empty($cardInfo['custom_field1']['name']) && $customField1['name'] = $cardInfo['custom_field1']['name'];
            $memberModel->custom_field1 = $customField1;
            //自定义会员信息类目二
            $customField2 = ['isopen'=>0,'name_type'=>'','name'=>'','url'=>''];
            $customField2['isopen'] = !empty($cardInfo['custom_field2']) ? 1 : 0;
            !empty($cardInfo['custom_field2']['name_type']) && $customField2['name_type'] = $cardInfo['custom_field2']['name_type'];
            !empty($cardInfo['custom_field2']['url']) && $customField2['url'] = $cardInfo['custom_field2']['url'];
            !empty($cardInfo['custom_field2']['name']) && $customField2['name'] = $cardInfo['custom_field2']['name'];
            $memberModel->custom_field2 = $customField2;
            //自定义会员信息类目三
            $customField3 = ['isopen'=>0,'name_type'=>'','name'=>'','url'=>''];
            $customField3['isopen'] = !empty($cardInfo['custom_field3']) ? 1 : 0;
            !empty($cardInfo['custom_field3']['name_type']) && $customField3['name_type'] = $cardInfo['custom_field3']['name_type'];
            !empty($cardInfo['custom_field3']['url']) && $customField3['url'] = $cardInfo['custom_field3']['url'];
            !empty($cardInfo['custom_field3']['name']) && $customField3['name'] = $cardInfo['custom_field3']['name'];
            $memberModel->custom_field3 = $customField3;
            //其他自定义会员信息类目一
            $customCell1 = ['isopen'=>0,'name'=>'','tips'=>'','url'=>''];
            $customCell1['isopen'] = !empty($cardInfo['custom_cell1']) ? 1 : 0;
            !empty($cardInfo['custom_cell1']['name']) && $customCell1['url'] = $cardInfo['custom_cell1']['name'];
            !empty($cardInfo['custom_cell1']['tips']) && $customCell1['tips'] = $cardInfo['custom_cell1']['tips'];
            !empty($cardInfo['custom_cell1']['url']) && $customCell1['url'] = $cardInfo['custom_cell1']['url'];
            $memberModel->custom_cell1 = $customCell1;
            //其他自定义会员信息类目二
            $customCell2 = ['isopen'=>0,'name'=>'','tips'=>'','url'=>''];
            $customCell2['isopen'] = !empty($cardInfo['custom_cell2']) ? 1 : 0;
            !empty($cardInfo['custom_cell2']['name']) && $customCell2['url'] = $cardInfo['custom_cell2']['name'];
            !empty($cardInfo['custom_cell2']['tips']) && $customCell2['tips'] = $cardInfo['custom_cell2']['tips'];
            !empty($cardInfo['custom_cell2']['url']) && $customCell2['url'] = $cardInfo['custom_cell2']['url'];
            $memberModel->custom_cell2 = $customCell2;
            //其他自定义会员信息类目三
            $customCell3 = ['isopen'=>0,'name'=>'','tips'=>'','url'=>''];
            $customCell3['isopen'] = !empty($cardInfo['custom_cell3']) ? 1 : 0;
            !empty($cardInfo['custom_cell3']['name']) && $customCell3['url'] = $cardInfo['custom_cell3']['name'];
            !empty($cardInfo['custom_cell3']['tips']) && $customCell3['tips'] = $cardInfo['custom_cell3']['tips'];
            !empty($cardInfo['custom_cell3']['url']) && $customCell3['url'] = $cardInfo['custom_cell3']['url'];
            $memberModel->custom_cell3 = $customCell3;
            //积分规则
            $bonusRule = ["cost_money_unit"=>0,"increase_bonus"=>0,"max_increase_bonus"=>0,"init_increase_bonus"=>0,"cost_bonus_unit"=>0,"reduce_money"=>0,"least_money_to_use_bonus"=>0,"max_reduce_bonus"=>0];
            !empty($cardInfo['bonus_rule']['cost_money_unit']) && $bonusRule['cost_money_unit'] = (int) $cardInfo['bonus_rule']['cost_money_unit'];
            !empty($cardInfo['bonus_rule']['increase_bonus']) && $bonusRule['increase_bonus'] = (int) $cardInfo['bonus_rule']['increase_bonus'];
            !empty($cardInfo['bonus_rule']['max_increase_bonus']) && $bonusRule['max_increase_bonus'] = (int) $cardInfo['bonus_rule']['max_increase_bonus'];
            !empty($cardInfo['bonus_rule']['init_increase_bonus']) && $bonusRule['init_increase_bonus'] = (int) $cardInfo['bonus_rule']['init_increase_bonus'];
            !empty($cardInfo['bonus_rule']['cost_bonus_unit']) && $bonusRule['cost_bonus_unit'] = (int) $cardInfo['bonus_rule']['cost_bonus_unit'];
            !empty($cardInfo['bonus_rule']['reduce_money']) && $bonusRule['reduce_money'] = (int) $cardInfo['bonus_rule']['reduce_money'];
            !empty($cardInfo['bonus_rule']['least_money_to_use_bonus']) && $bonusRule['least_money_to_use_bonus'] = (int) $cardInfo['bonus_rule']['least_money_to_use_bonus'];
            !empty($cardInfo['bonus_rule']['max_reduce_bonus']) && $bonusRule['max_reduce_bonus'] = (int) $cardInfo['bonus_rule']['max_reduce_bonus'];
            $memberModel->bonus_rule = $bonusRule;
            //折扣，该会员卡享受的折扣优惠,填10就是九折
            $memberModel->discount = !empty($cardInfo['discount']) ? (int) $cardInfo['discount'] : 0;
            $memberModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 刷新领卡用户数据
     * @param $cardId
     * @param $userCode
     * @return bool
     * @throws \Exception
     */
    public function upsetUserinfo($cardId, $userCode)
    {
        \DB::beginTransaction();
        try {
            $app = EasyWechat::officialAccount();
            $apiRs = $app->card->member_card->getUser($cardId, $userCode);
            WxErrorService::checkApiResponse($apiRs);
            //更新本地数据
            $memberListModel = WxCardMemberList::where('user_card_code', $userCode)->where('card_id', $cardId)->first();
            if (empty($memberListModel)) {
                $memberListModel = new WxCardMemberList;
                $memberListModel->card_id = $cardId;
                $memberListModel->user_card_code = $userCode;
            }
            //卡券主表ID
            $cardData = (new WxCardService())->getCardByCardId($cardId);
            !empty($cardData) && $memberListModel->card_base_id = $cardData['card_base_id'];
            isset($apiRs['openid']) && $memberListModel->openid = $apiRs['openid'];
            isset($apiRs['nickname']) && $memberListModel->nickname = $apiRs['nickname'];
            isset($apiRs['sex']) && $memberListModel->sex = $apiRs['sex'];
            isset($apiRs['bonus']) && $memberListModel->bonus = $apiRs['bonus'];
            isset($apiRs['balance']) && $memberListModel->balance = $apiRs['balance'];
            isset($apiRs['user_info']) && $memberListModel->user_info = $apiRs['user_info'];
            isset($apiRs['user_card_status']) && $memberListModel->user_card_status = $apiRs['user_card_status'];
            isset($apiRs['has_active']) && $memberListModel->has_active = (int)$apiRs['has_active'];
            $memberListModel->save();

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        //调用扩展类更新对应用户卡券信息，如用户等级、积分、优惠券等
        if (!empty($cardData['card_key']) && $memberListModel->has_active == 1){
            $memberCardObj = __NAMESPACE__ . '\MemberCard\\' . camelizeClass($cardData['card_key']);
            $memberListId = !empty($memberListModel->id) ? (int) $memberListModel->id : 0;
            if (class_exists($memberCardObj)){
                (new $memberCardObj())->updateUserCardData($memberListId);
            }
        }

        return true;
    }

    /**
     * 通过会员卡ID获取会员卡
     * @param $memberListId
     * @return array
     */
    public function getMemberDataById($memberListId)
    {
        $memberModel = WxCardMemberList::find($memberListId);
        $memberListData = $memberModel ? $memberModel->toArray() : [];
        $memberListData['user_info'] = $this->fomatUserInfo($memberListData['user_info']);
        return $memberListData;
    }
    /**
     * 格式化用户注册信息
     * @param $originUserInfo
     * @return array
     */
    public function fomatUserInfo($originUserInfo)
    {
        //将用户输入数据统一为同一种格式
        $newUserInfo = ['field_list'=>[]];
        //解析微信通用字段
        if (!empty($originUserInfo['common_field_list'])){
            foreach ($originUserInfo['common_field_list'] as $fieldVal){
                //手机号
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_MOBILE'){
                    $newUserInfo['mobile'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '手机号','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //性别
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_SEX'){
                    $newUserInfo['sex'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '性别','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //姓名
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_NAME'){
                    $newUserInfo['name'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '姓名','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //生日
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_BIRTHDAY'){
                    $newUserInfo['birthday'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '生日','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //身份证
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_IDCARD'){
                    $newUserInfo['idcard'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '身份证','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //邮箱
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_EMAIL'){
                    $newUserInfo['email'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '邮箱','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //详细地址
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_LOCATION'){
                    $newUserInfo['location'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '详细地址','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //教育背景
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_EDUCATION_BACKGRO'){
                    $newUserInfo['education_backgro'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '教育背景','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //行业
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_INDUSTRY'){
                    $newUserInfo['industry'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '行业','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //收入
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_INCOME'){
                    $newUserInfo['income'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '收入','value'=>$fieldVal['value'],'type'=>'common'];
                }
                //兴趣爱好
                if ($fieldVal['name'] == 'USER_FORM_INFO_FLAG_HABIT'){
                    $newUserInfo['habit'] = $fieldVal['value'];
                    $newUserInfo['field_list'][] = ['name' => '兴趣爱好','value'=>$fieldVal['value'],'type'=>'common'];
                }
            }
        }
        //解析自定义字段信息
        if (!empty($originUserInfo['custom_field_list'])){
            foreach ($originUserInfo['custom_field_list'] as $fieldVal){
                $newUserInfo['field_list'][] = [
                    'name' => $fieldVal['name'],
                    'value'=>!empty($fieldVal['value']) ? $fieldVal['value'] : (!empty($fieldVal['value_list']) ? implode('、', $fieldVal['value_list']): '' ),
                    'type'=>'custom'
                ];
            }
        }
        return $newUserInfo;
    }
    /**
     * 获取指定卡券ID、等级ID、开始结束时间内的会员总数
     * @param $cardBaseId
     * @param $levelId
     * @param string $startTime
     * @param string $endTime
     * @return mixed
     */
    public function getCount($where = [])
    {
        $query = WxCardMemberList::select('*');
        if (!empty($where['cardBaseId'])){
            $query->where('card_base_id', $where['cardBaseId']);
        }
        if (!empty($where['levelId'])){
            $query->where('level_id', $where['levelId']);
        }
        if (!empty($where['startTime']) && !empty($where['endTime'])){
            $query->whereBetween('created_at', [$where['startTime'], $where['endTime']]);
        }
        $query->where('has_active', 1);
        return $query->count();
    }
}